<?php

namespace App\Http\Controllers;

use App\ImUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

/**
 * 登录控制器
 * Class LoginController
 * @package App\Http\Controllers
 */
class LoginController extends Controller
{
    //加载登录页面
    public function index()
    {
        return view('login.index');
    }

    /**
     * 登录操作方法
     * @param (int)Request $request->tel 手机
     * @param (string)Request $request->password 密码
     */
    public function loginOperation(Request $request)
    {
        $user = ImUser::where('tel', $request->tel)->first();
        if ($user) {
            //验证密码,密码正确就登录
            if (Hash::check($request->password, $user['password'])) {
                session(['user' => [
                    'id' => $user['id'],
                    'tel' => $user['tel']
                ]]);
                return redirect()->route('im.indexList');
            }
        } else {
            //找不到用户,执行注册
            $id = ImUser::insertGetId([
                'created_at'=>date('Y-m-d H:i:s'),
                'tel' => $request->tel,
                'password' => Hash::make($request->password),
            ]);
            session(['user' => [
                'id' => $id,
                'tel' => $request->tel
            ]]);
            return redirect()->route('im.indexList');
        }
    }

    /**
     * 退出登录
     */
    public function loginOut(){
        session()->forget('user');//删除登录信息
    }
}
